<template>
  <div class="container">
    <a-button @click="showAdd = true">新增题库</a-button>

    <!-- 题库列表 -->
    <a-table :columns="columns" :data="tableData" :pagination="false">
      <template #tags="{ record }">
        <a-space>
          <a-tag v-for="item of record.tags.split(',')" :key="item">
            {{ item }}
          </a-tag>
        </a-space>
      </template>
      <template #type="{ record }">
        <span v-if="record.type === 1"> 笔试真题</span>
        <span v-else-if="record.type === 2"> 录音</span>
        <span v-else> 常规题</span>
      </template>
      <template #action="{ record }">
        <a-button>编辑</a-button>
        <a-popconfirm content="别了吧？" @ok="handleDel(record)">
          <a-button>删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>
    <a-pagination
      :total="total"
      show-page-size
      @change="handlePageChange"
      @page-size-change="handleSizeChange"
    />

    <!-- 添加的弹窗 -->
    <a-modal
      v-model:visible="showAdd"
      fullscreen
      :footer="false"
      unmount-on-close
      @ok="handleOk"
      @open="handleOpen"
    >
      <template #title>
        <div class="hdques">
          <span></span>
          <span>添加题目 </span>
          <a-button type="primary" status="success" @click="handleAdd">
            确定添加
          </a-button>
        </div>
      </template>
      <!-- 新增的表单 -->
      <a-form ref="myform" :model="addform">
        <!-- 公司名称 -->
        <a-form-item
          :rules="[{ required: true, message: '公司名称不能为空' }]"
          :validate-trigger="['change', 'input']"
          field="companyId"
          tooltip="请输入公司的名称"
          label="名称"
        >
          <!-- <a-auto-complete
            v-model="addform.companyName"
            :data="company.map((item) => item.name)"
            :style="{ width: '360px' }"
            placeholder="please enter something"
            strict
          /> -->
          <a-select v-model="addform.companyId" allow-search>
            <a-option v-for="item of company" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <!-- 标题 -->
        <a-form-item
          :rules="[{ required: true, message: '标题不能为空' }]"
          :validate-trigger="['change', 'input']"
          field="title"
          tooltip="请输入标题"
          label="标题"
        >
          <a-input
            v-model="addform.title"
            placeholder="请输入一个标题"
          ></a-input>
        </a-form-item>

        <!-- 类型 -->
        <a-form-item field="type" label="题目类型">
          <a-radio-group v-model="addform.type" default-value="笔试真题">
            <template v-for="(item, index) in types" :key="item">
              <a-radio :value="index + 1">
                <template #radio="{ checked }">
                  <a-space
                    align="start"
                    class="custom-radio-card"
                    :class="{ 'custom-radio-card-checked': checked }"
                  >
                    <div className="custom-radio-card-mask">
                      <div className="custom-radio-card-mask-dot" />
                    </div>
                    <div>
                      <div className="custom-radio-card-title">
                        {{ item }}
                      </div>
                      <a-typography-text type="secondary"> </a-typography-text>
                    </div>
                  </a-space>
                </template>
              </a-radio>
            </template>
          </a-radio-group>
        </a-form-item>
        <!-- 题目标签-->
        <a-form-item field="type" label="题目类型">
          <div>
            <div>
              <a-space>
                <a-tag
                  v-for="(item, index) of addform.tags"
                  :key="index"
                  color="gray"
                >
                  {{ item }}
                </a-tag>
                <a-input
                  v-if="addNewTag"
                  v-model.trim="newtag"
                  @keyup.enter="handleTagInput"
                  @blur="handleTagInput"
                />
                <a-tag v-else @click="addNewTag = true">添加新的标签</a-tag>
              </a-space>
            </div>
            <div class="cusTag">
              <span> 点击可以快捷选择的标签： </span>:
              <div class="tags">
                <span @click="handleAddTag('vue')"> vue </span>
                <span @click="handleAddTag('react')"> react </span>
                <span @click="handleAddTag('js')"> js </span>
              </div>
            </div>
          </div>
        </a-form-item>

        <!-- 真题上传 -->

        <template v-if="addform.type === 1">
          <a-upload
            action="http://www.wzsqyg.com/attachment/upload"
            name="file"
            :data="{ type: 'qf2210a' }"
            @success="handleImgUplaod"
          >
            <template #upload-button>
              <a-button> 上传真题图片自动识别</a-button>
            </template>
          </a-upload>
        </template>
        <!-- 音频上传 -->
        <template v-if="addform.type === 2">
          <a-upload
            :file-list="fileList"
            draggable
            action="http://www.wzsqyg.com/attachment/upload"
            name="file"
            :limit="1"
            :data="{
              type: '2210a',
            }"
            @success="handleUploadSuccess"
          />
          <audio id="player"></audio>
        </template>
        <template v-else>
          <v-md-editor
            ref="mdeditor"
            v-model="tt"
            :disabled-menus="[]"
            height="400px"
            @change="handleEdChange"
            @upload-image="handleUpload"
          ></v-md-editor>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<!-- <script src="./index.js"></script> -->
<script setup>
  import { ref, reactive, onMounted, watch, nextTick } from 'vue';
  import { getCompany } from '@/api/company';
  import { addQuestion, getQuestion } from '@/api/question';
  import { Message, Notification } from '@arco-design/web-vue';
  import axios from 'axios';
  import Plyr from 'plyr';
  import { createWorker } from 'tesseract.js';

  // 新增题目的流程
  const showAdd = ref(false);

  const handleOk = () => {};
  const addform = reactive({
    companyId: '',
    title: '',
    tags: [],
    type: 1,
    desc: '',
  });
  const company = ref([]);
  const getCompanyList = async () => {
    const res = await getCompany({ $limit: 10000 });
    company.value = res.data.data;
  };

  // 动态添加标签
  const addNewTag = ref(false);
  const newtag = ref('');

  const handleTagInput = () => {
    if (!newtag.value) {
      Message.warning('该标签已经存在');
      addNewTag.value = false;
      return false;
    }
    const one = addform.tags.find((item) => item === newtag.value);
    if (one) {
      addNewTag.value = false;
      return Message.warning('该标签已经存在');
    }
    addform.tags.push(newtag.value);
    newtag.value = '';
    addNewTag.value = false;
    return false;
  };
  const handleAddTag = (val) => {
    const one = addform.tags.find((item) => item === val);
    if (!one) return addform.tags.push(val);
    Message.warning('该标签已经存在');
    return false;
  };
  onMounted(() => {
    getCompanyList();
  });
  const types = ['笔试真题', '面试录音', '常规题'];
  const fileList = ref([]);

  // 播放器的流程
  const player = ref();
  const audio = ref('');
  const handleUploadSuccess = (fileItem) => {
    console.log('fileItem', fileItem);
    player.value = new Plyr('#player');
    audio.value = fileItem.response.msg;
    player.value.source = {
      type: 'audio',
      title: '录音内容',
      sources: [
        {
          src: fileItem.response.msg,
          type: 'audio/mp3',
        },
      ],
    };
  };
  // const handleOpen = () => {
  //   console.log(document.getElementById('player'));
  //   player.value = new Plyr('#player');
  // };

  // watch(
  //   addform,
  //   (nv) => {
  //     const { type } = nv;
  //     if (type === '面试录音') {
  //       nextTick(() => {
  //         player.value = new Plyr('#player');
  //       });
  //     }
  //   },
  //   {
  //     deep: true,
  //   }
  // );

  // 处理图片的上传
  const handleUpload = async (event, insertImage, files) => {
    console.log('files', files);
    const file = files[0];
    const form = new FormData();
    form.append('file', file);
    form.append('type', 'qf2210a');
    Notification.info('上传中');
    const res = await axios.post(
      'http://www.wzsqyg.com/attachment/upload',
      form
    );
    console.log('res', res);
    Notification.success('上传完成');
    insertImage({
      url: res.data.msg,
      desc: res.data.msg.split('/').pop(),
    });
  };

  // 公司名称的检索
  const handleSearch = () => {};

  const reset = () => {
    addform.companyId = '';
    addform.title = '';
    addform.tags = [];
    addform.type = '笔试真题';
    addform.content = '';
    fileList.value = [];
  };

  // 确定添加
  const handleAdd = async () => {
    const res = await addQuestion({
      ...addform,
      tags: addform.tags.join(),
      audio: audio.value,
    });
    const { status } = res;
    if (status === 201) {
      Message.success('添加成功');
      // showAdd.value = false;
      // reset();
    } else {
      Message.warning('添加出错');
    }
  };

  // 列表查询
  const tableData = ref([]);
  const limit = ref(20);
  const total = ref(0);
  const page = ref(1);

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      width: 300,
    },
    {
      title: '分类',
      slotName: 'type',
      width: 200,
    },
    {
      title: '标签',
      slotName: 'tags',
    },
    {
      title: '操作',
      slotName: 'action',
    },
  ];
  const getList = async () => {
    const params = {
      '$limit': limit.value,
      '$skip': (page.value - 1) * limit.value,
      '$sort[id]': -1,
    };

    const res = await getQuestion(params);
    tableData.value = res.data.data;
    total.value = res.data.total;
  };

  onMounted(getList);

  const tt = ref('');
  const handleEdChange = (txt, html) => {
    addform.desc = html;
  };

  // 处理上传的图片

  const bytesseract = async (img) => {
    const worker = await createWorker({
      logger: (m) => console.log(m),
    });

    await worker.loadLanguage('eng+chi_sim');
    await worker.initialize('chi_sim');
    const {
      data: { text },
    } = await worker.recognize(img);
    console.log('识别的文字结果', text);
    await worker.terminate();
  };

  const mdeditor = ref(null);
  const handleImgUplaod = async (fileItem) => {
    console.log('fileItem', fileItem);
    // bytesseract(fileItem.response.msg)

    Notification.info('图片识别中');
    const res = await axios.post(
      'http://subject12.market.alicloudapi.com/educationservice/papercut',
      {
        urlList: [fileItem.response.msg],
        paperType: 'question',
        templateType: 'default',
        image_correction: true,
      },
      {
        headers: {
          Authorization: 'APPCODE 092a111065d6469982db25134a0520f7',
        },
        contentType: 'application/json; charset=utf-8',
      }
    );

    Notification.success('识别完成');

    // eslint-disable-next-line
    const { subject_list } = res.data.page_list[0];

    let content = '';
    // eslint-disable-next-line
    for (const item of subject_list) {
      content += `<p> ${item.text} </p>`;
    }

    mdeditor.value.insert(() => {
      return {
        text: content,
      };
    });
    setTimeout(() => {
      mdeditor.value.insert(() => {
        return {
          text: `<img src='${fileItem.response.msg}'  /> `,
        };
      });
    }, 0);
  };
</script>

<style lang="scss" scoped>
  @import url('./style.scss');
</style>
